﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UIShare;
using EFong.View.Proxy;
using EFong.View.Customer;
using DevExpress.XtraBars;

namespace EFong.View.HotelBooking
{
    public partial class Frm_HotelBookingEdit : BasicForm
    {
        private Proxy.BaseServiceProxy _baseProxy { get { return Proxy.BaseServiceProxy.GetInstance(); } }
        private Proxy.MasterServiceProxy _masterProxy { get { return Proxy.MasterServiceProxy.GetInstance(); } }
        private Proxy.BusinessServiceProxy _businessProxy { get { return Proxy.BusinessServiceProxy.GetInstance(); } }

        public Contract.RHotelBooking ReturnValue = null;

        public Frm_HotelBookingEdit()
        {
            InitializeComponent();
            //spe_HotelTax.SetValue(null);
            spe_BasePriceOrVendorDiscount.SetValue(null);
            spe_PrintTotalPrice.SetValue(null);

            //cmb_BankAccount.ReadOnly(true);
        }

        protected override void InitFields()
        {
        }

        protected override void Events()
        {
            this.gv_Details.FocusedRowChanged += (s, e) =>
                {
                    Detail = this.gv_Details.GetRow(e.FocusedRowHandle) as Contract.HotelBookingDetail;
                };
            this.btn_CustomerData.Click += (s, e) =>
                {
                    editCustomer();
                };
            this.cmb_Customer.EditValueChanged += (s, e) =>
            {
                Contract.RCustomer customer = this.cmb_Customer.GetValue() as Contract.RCustomer;

                if (customer != null)
                {
                    SelCust = _masterProxy.GetCustomerByID(customer.ID).ReturnValue;
                }
                else
                {
                    SelCust = null;
                }
            };
            this.cmb_Vendor.EditValueChanged += (s, e) =>
            {
                Contract.RVendor vendor = this.cmb_Vendor.GetValue() as Contract.RVendor;

                if (vendor != null)
                {
                    SelVend = _masterProxy.GetVendorByID(vendor.ID).ReturnValue;
                }
                else
                {
                    SelVend = null;
                }
            };

            //this.cmb_PaymentType.SelectedIndexChanged += (s, e) =>
            //{
            //    if (ViewState == ViewStates.EDIT) { return; }

            //    this.cmb_BankAccount.SetValue(default(Contract.BankAccount));
            //    this.cmb_BankAccount.ReadOnly(this.cmb_PaymentType.SelectedIndex <= 0);

            //    //if (this.cmb_PaymentType.SelectedIndex == 0)
            //    this.cmb_VendorCurrency.SetValue(_baseProxy.GetCNYCurrency().ReturnValue);
            //    //else
            //    //    this.cmb_VendorCurrency.SetValue(default(Contract.Currency));
            //};
            //this.cmb_BankAccount.SelectedIndexChanged += (s, e) =>
            //{
            //    Contract.BankAccount bank = this.cmb_BankAccount.GetValue() as Contract.BankAccount;
            //    if (bank != null)
            //    {
            //        cmb_VendorCurrency.ReadOnly(true);
            //        this.cmb_VendorCurrency.SetValue(bank.Currency);
            //    }
            //    else
            //    {
            //        cmb_VendorCurrency.ReadOnly(false);
            //        this.cmb_VendorCurrency.SetValue(default(Contract.Currency));
            //    }
            //};

            this.cmb_CustomerPaymentType.SelectedIndexChanged += (s, e) =>
                {
                    updateOrderTotalFields();
                    onDetailChanged();
                };
        }

        protected override void LoadDatas()
        {
            bds_Customer.BindingData(_masterProxy.GetAllCustomer().ReturnValue);
            bds_Vendor.BindingData(_masterProxy.GetAllHotelVendor().ReturnValue);
            this.cmb_OrderTicketUser.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);
            this.cmb_ProvideTicketUser.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);
            this.cmb_OrderUser.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);
            this.cmb_SalesMan.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);

            //this.cmb_BankAccount.Properties.BindingData(_masterProxy.GetAllEffectivedBankAccount());
            this.cmb_VendorCurrency.Properties.BindingData(_baseProxy.GetAllCurrency().ReturnValue);

            if (this.cmb_OrderUser.GetValue() == null)
                this.cmb_OrderUser.SetValue(AppParameters.LoginUser);
        }

        private void bar_Main_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "bbt_Add":
                    this.add();
                    break;
                case "bbt_Edit":
                    this.edit();
                    break;
                case "bbt_Save":
                    this.save();
                    break;
                case "bbt_Close":
                    this.Close();
                    break;
                default:
                    break;
            }
        }

        private void add()
        {
            Frm_HotelBookingDetailEdit frm = new Frm_HotelBookingDetailEdit();
            frm.Text = "增加订单明细";
            frm.ViewState = this.ViewState;
            frm.Load += (s, e) =>
                {
                    frm.Detail = new Contract.HotelBookingDetail() { HotelBooking = getOrder() };
                };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
            {
                this.gv_Details.BeginDataUpdate();
                ((List<Contract.HotelBookingDetail>)this.bds_hotelBookingDetail.DataSource).Add(frm.Detail);
                this.gv_Details.EndDataUpdate();
                updateOrderTotalFields();
            }
        }

        private void edit()
        {
            Frm_HotelBookingDetailEdit frm = new Frm_HotelBookingDetailEdit();
            frm.Text = "修改订单明细";
            frm.ViewState = this.ViewState;
            frm.Load += (s, e) =>
                {
                    frm.Detail = Detail;
                };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
            {
                this.gv_Details.BeginDataUpdate();
                this.gv_Details.EndDataUpdate();
                Detail = frm.Detail;
                updateOrderTotalFields();
            }
        }

        private string returnRef;

        private void save()
        {
            Contract.HotelBooking order = null;

            UIOperManager.SaveData(
                () =>
                {
                    return true;
                },
                () =>
                {
                    order = getOrder();
                    updateToOrder(order);
                    var result = _businessProxy.UpdateHotelBooking(Order);
                    if (result.IsSuccess)
                    {
                        returnRef = result.ReturnValue;
                        this.txt_OrderRef.Text = returnRef;
                    }

                    return result.IsSuccess;
                },
                string.Empty,
                () =>
                {
                    DialogResult = DialogResult.OK;
                    MsgBox.Info(string.Format("{0} 保存成功", returnRef));
                    this.Close();

                    ReturnValue = new Contract.RHotelBooking()
                    {
                        ID = Order.ID,
                        Customer = Order.Customer.Name,
                        CustomerStatus = Order.CustomerStatus,
                        Intergral = Order.TotalIntergral.Value,
                        OrderDate = Order.OrderDate,
                        OrderUserText = Order.OrderUser.Name,
                        Ref = returnRef,
                        Remark = Order.Remark,
                        Status = Order.Status,
                        TotalPrice = Order.TotalPrice.Value,
                        VendorStatus = Order.VendorStatus
                    };
                });
        }

        private void editCustomer()
        {
            if (SelCust == null)
                return;

            Frm_CustomerEdit frm = new Frm_CustomerEdit();
            frm.Text = "客户详细资料";
            if (!AppParameters.AllowEditCustomer)
                frm.ViewState = ViewStates.BROWSER;
            frm.Load += (s, e) =>
            {
                frm.CurCust = SelCust;
            };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
                SelCust = frm.CurCust;
        }

        private void updateOrderTotalFields()
        {
            Contract.HotelBooking order = getOrder();

            this.txt_OrderTotalPrice.SetText(order.TotalPrice);
            this.txt_OrderTotalProfit.SetText(order.TotalProfit);
            this.txt_OrderTotalVendorPrice.SetText(order.TotalVendorPrice);
            this.txt_OrderTotalIntegralExchange.SetText(order.TotalIntergral);
        }

        #region Order
        // current hotel booking
        private Contract.HotelBooking _order;
        public Contract.HotelBooking Order
        {
            get { return _order; }
            set
            {
                _order = value;
                onOrderChanged();
            }
        }

        private void onOrderChanged()
        {
            if (Order == null)
            {
                //ControlExtensions.ClearValue(
                //        txt_OrderRef,
                //        txt_OrderUser,
                //        dte_OrderDate,
                //        cmb_Customer,
                //        cmb_Vendor,
                //        txt_OrderTicketUser,
                //        cmb_PaymentType,
                //        cmb_Currency,
                //        spe_ExchangeRate,
                //        spe_PrintTotalPrice,
                //        txt_OrderRemark,
                //        txt_OrderTotalPrice,
                //        txt_OrderTotalVendorPrice,
                //        txt_OrderTotalProfit
                //    );
                //this.bds_hotelBookingDetail.BindingData(new List<Contract.HotelBookingDetail>());
            }
            else
            {
                if (Order.OrderUser != null)
                    this.cmb_OrderUser.SetValue(Order.OrderUser);
                if (Order.OrderDate != null)
                    this.dte_OrderDate.SetValue(Order.OrderDate);
                this.txt_OrderRef.SetText(Order.Ref);
                if (Order.Ref == string.Empty)
                    this.txt_OrderRef.SetText("(保存时自动获取)");
                this.cmb_Customer.SetValue(Order.Customer);
                SelCust = Order.Customer;
                if (Order.Vendor != null)
                {
                    Contract.RVendor vendor = new Contract.RVendor();
                    vendor.ID = Order.Vendor.ID;
                    vendor.Name = Order.Vendor.Name;
                    this.cmb_Vendor.SetValue(vendor);
                }
                SelVend = Order.Vendor;
                this.cmb_OrderTicketUser.SetValue(Order.OrderHotelUser);

                this.txtAddress.SetText(Order.Address);
                this.txt_CPerson.SetText(Order.ContactPerson);
                this.txt_CPersonTel.SetText(Order.联系电话);
                this.txt_CPersonPhone.SetText(Order.移动电话);

                this.cmb_ProvideTicketUser.SetValue(Order.ProvideTicketUser);
                this.dte_ProvideTicketDate.SetValue(Order.ProvideTicketDate);
                this.dte_DeliveryTicketDate.SetValue(Order.DeliveryDate);

                this.cmb_CustomerPaymentType.SetText(Order.CustomerPaymentType);
                this.spe_ExchangeRate.SetValue(Order.ExchangeRate);
                this.spe_PrintTotalPrice.SetValue(Order.PrintTotalPrice);
                this.txt_OrderRemark.SetText(Order.Remark);
                this.cmb_SalesMan.SetValue(Order.Salesman);

                //this.cmb_PaymentType.SetDisplay(Order.PaymentType);
                //if (Order.BankAccount != null)
                //    this.cmb_BankAccount.SetValue(Order.BankAccount);
                if (Order.VendorCurrency != null)
                    this.cmb_VendorCurrency.SetValue(Order.VendorCurrency);
                else
                    this.cmb_VendorCurrency.SetValue(_baseProxy.GetCNYCurrency().ReturnValue);

                this.txt_OrderTotalPrice.SetText(Order.TotalPrice);
                this.txt_OrderTotalProfit.SetText(Order.TotalProfit);
                this.txt_OrderTotalVendorPrice.SetText(Order.TotalVendorPrice);
                this.txt_OrderTotalIntegralExchange.SetText(Order.TotalIntergral);

                this.bds_hotelBookingDetail.BindingData(Order.Details);
            }
        }

        private Contract.HotelBooking getOrder()
        {
            Contract.HotelBooking order = new Contract.HotelBooking();

            order.Address = this.txtAddress.GetText();
            order.OrderUser = this.cmb_OrderUser.GetValue() as Contract.User;
            order.OrderDate = this.dte_OrderDate.GetValue(AppParameters.FetureDateTime);
            order.Customer = SelCust;
            order.Vendor = SelVend;
            order.OrderHotelUser = this.cmb_OrderTicketUser.GetValue() as Contract.User;
            order.CustomerPaymentType = this.cmb_CustomerPaymentType.GetDisplay();
            order.ExchangeRate = this.spe_ExchangeRate.GetValue();
            order.PrintTotalPrice = this.spe_PrintTotalPrice.GetValue(true);
            order.Remark = this.txt_OrderRemark.GetText();
            if (this.bds_hotelBookingDetail.DataSource as List<Contract.HotelBookingDetail> != null)
            {
                order.Details = this.bds_hotelBookingDetail.DataSource as List<Contract.HotelBookingDetail>;
                foreach (var detail in order.Details)
                    detail.HotelBooking = order;
            }
            order.Salesman = this.cmb_SalesMan.GetValue() as Contract.User;
            order.Currency = _baseProxy.GetCNYCurrency().ReturnValue;

            order.ContactPerson = this.txt_CPerson.GetText();
            order.联系电话 = this.txt_CPersonTel.GetText();
            order.移动电话 = this.txt_CPersonPhone.GetText();

            order.ProvideTicketUser = this.cmb_ProvideTicketUser.GetValue() as Contract.User;

            if (this.dte_ProvideTicketDate.GetValue().HasValue)
                order.ProvideTicketDate = this.dte_ProvideTicketDate.GetValue().Value;

            if (this.dte_DeliveryTicketDate.GetValue().HasValue)
                order.DeliveryDate = this.dte_DeliveryTicketDate.GetValue().Value;

            //order.BankAccount = this.cmb_BankAccount.GetValue() as Contract.BankAccount;
            //order.PaymentType = this.cmb_PaymentType.GetDisplay();
            order.VendorCurrency = this.cmb_VendorCurrency.GetValue() as Contract.Currency;

            return order;
        }

        private void updateToOrder(Contract.HotelBooking order)
        {
            Order.Address = order.Address;
            Order.Customer = order.Customer;
            Order.Details = order.Details;
            Order.ExchangeRate = order.ExchangeRate;
            Order.OrderDate = order.OrderDate;
            Order.OrderHotelUser = order.OrderHotelUser;
            Order.OrderUser = order.OrderUser;
            Order.CustomerPaymentType = order.CustomerPaymentType;
            Order.PrintTotalPrice = order.PrintTotalPrice;
            Order.Remark = order.Remark;
            Order.Vendor = order.Vendor;
            Order.Salesman = order.Salesman;
            Order.Currency = order.Currency;

            Order.ContactPerson = order.ContactPerson;
            Order.联系电话 = order.联系电话;
            Order.移动电话 = order.移动电话;

            Order.PaymentType = order.PaymentType;
            Order.BankAccount = order.BankAccount;
            Order.VendorCurrency = order.VendorCurrency;

            Order.ProvideTicketUser = order.ProvideTicketUser;
            Order.ProvideTicketDate = order.ProvideTicketDate;
            Order.DeliveryDate = order.DeliveryDate;

            foreach (var detail in Order.Details)
            {
                detail.HotelBooking = Order;
            }
        }
        #endregion

        #region Detail
        private Contract.HotelBookingDetail _detail;
        public Contract.HotelBookingDetail Detail
        {
            get { return _detail; }
            set
            {
                _detail = value;
                onDetailChanged();
            }
        }

        private void onDetailChanged()
        {
            if (Detail == null)
            {
                ControlExtensions.ClearValue(
                    dte_CheckInDate,
                    dte_CheckOutDate,
                    txt_GuestName,
                    txt_ConfirmationRef,
                    txt_HotelName,
                    txt_HotelOrderRef,
                    spe_HotelTax,
                    spe_Price,
                    txt_HotelLevel,
                    spe_Rooms,
                    txt_RoomType,
                    txt_TotalPrice,
                    txt_TotalVendorPrice,
                    txt_TotalProfit,
                    txt_TotalIntegralExchange);
            }
            else
            {
                this.dte_CheckInDate.SetValue(Detail.CheckInDate);
                this.dte_CheckOutDate.SetValue(Detail.CheckOutDate);
                this.txt_GuestName.SetText(Detail.GuestName);
                this.txt_ConfirmationRef.SetText(Detail.HotelConfirmationRef);
                this.txt_HotelName.SetText(Detail.HotelName);
                this.txt_HotelOrderRef.SetText(Detail.HotelOrderRef);
                this.spe_HotelTax.SetValue(Detail.HotelTax);
                this.spe_Price.SetValue(Detail.Price);
                this.txt_HotelLevel.SetText(Detail.HotelLeave);
                this.spe_Rooms.SetValue(Detail.Rooms);
                this.txt_RoomType.SetText(Detail.RoomType);

                if (Detail.VendorDiscount.HasValue)
                {
                    this.rad_VendorDiscount.Checked = true;
                    this.spe_BasePriceOrVendorDiscount.SetValue(Detail.VendorDiscount);
                }
                else if (Detail.VendorPrice.HasValue)
                {
                    this.rad_BasePrice.Checked = true;
                    this.spe_BasePriceOrVendorDiscount.SetValue(Detail.VendorPrice);
                }
                else
                {
                    this.rad_BasePrice.Checked = this.rad_VendorDiscount.Checked = false;
                    this.spe_BasePriceOrVendorDiscount.SetValue(null);
                }

                this.spe_Days.SetValue(Detail.Days);
                this.txt_TotalPrice.SetText(Detail.TotalPrice);
                this.txt_TotalProfit.SetText(Detail.Profit);
                this.txt_TotalVendorPrice.SetText(Detail.TotalVendorPrice);
                this.txt_TotalIntegralExchange.SetText(Detail.Intergral);
            }
        }
        #endregion

        #region Customer
        private Contract.Customer _selCust;
        public Contract.Customer SelCust
        {
            get { return _selCust; }
            set
            {
                _selCust = value;
                onSelCustChanged();
            }
        }

        private void onSelCustChanged()
        {
            if (SelCust == null)
            {
                this.cmb_SalesMan.SetValue(default(Contract.User));
                this.txt_CPerson.SetText(null);
                this.txt_CPersonTel.SetText(null);
                this.txt_CPersonPhone.SetText(null);
                this.txtAddress.SetText(null);
            }
            else
            {
                this.txtAddress.SetText(SelCust.Address);
                this.cmb_SalesMan.SetValue(SelCust.Salesman);
                this.txt_CPerson.SetText(SelCust.ContactPerson1);
                this.txt_CPersonTel.SetText(SelCust.ContactPerson1Tel);
                this.txt_CPersonPhone.SetText(SelCust.ContactPerson1Phone1);
            }
        }
        #endregion

        #region Vendor
        public Contract.Vendor SelVend { get; set; }
        #endregion


        protected override void OnViewStateChanged()
        {
            switch (ViewState)
            {
                case ViewStates.ADD:
                    bbt_Add.Visibility = BarItemVisibility.Always;
                    break;
                case ViewStates.EDIT:
                    bbt_Add.Visibility = BarItemVisibility.Never;
                    if (!AppParameters.IsAdRole)
                    {
                        spe_ExchangeRate.ReadOnly(true);
                        cmb_VendorCurrency.ReadOnly(true);
                        //cmb_BankAccount.ReadOnly(true);
                        //cmb_PaymentType.ReadOnly(true);
                        cmb_Vendor.ReadOnly(true);
                        cmb_Customer.ReadOnly(true);
                        cmb_CustomerPaymentType.ReadOnly(true);
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
